import {
    AllChannels,
    ApiRes,
    Articles,
    Channel,
    UserChannel,
} from "@/types/data";
import { RootThunkAction } from "@/types/store";
import { http } from "@/utils/http";

const CHANNEL_KEY = "geek-channels";
// 获得用户频道
export const getUserChannels = (): RootThunkAction => {
    return async (dispatch, getState) => {
        const token = getState().login.token;
        let userChannel: Channel[] = [];
        // 登录
        if (token) {
            const res = await http.get<ApiRes<UserChannel>>("/user/channels");
            const { channels } = res.data.data;
            userChannel = channels;
        } else {
            const localChannels = JSON.parse(
                localStorage.getItem(CHANNEL_KEY) ?? "[]"
            ) as Channel[];
            if (localChannels.length > 0) {
                userChannel = localChannels;
            } else {
                const res = await http.get<ApiRes<UserChannel>>(
                    "/user/channels"
                );
                const { channels } = res.data.data;
                localStorage.setItem(CHANNEL_KEY, JSON.stringify(channels));
                userChannel = channels;
            }
        }
        dispatch({
            type: "home/getUserChannel",
            payload: userChannel,
        });
    };
};
// 获得全部频道(并处理推荐频道)
export const getAllChannel = (): RootThunkAction => {
    return async (dispatch, getState) => {
        const res = await http.get<ApiRes<AllChannels>>("/channels");
        const { userChannel } = getState().home;
        // 推荐的频道
        const restChannels = res.data.data.channels.filter((item) => {
            return userChannel.every((item1) => item1.id !== item.id);
        });
        dispatch({
            type: "home/getAllChannel",
            payload: restChannels,
        });
    };
};
// 删除频道
export const delChannel = (channel: Channel): RootThunkAction => {
    return async (dispatch, getState) => {
        const {
            login: { token },
        } = getState();

        if (token) {
            // 已登录
            await http.delete(`/user/channels/${channel.id}`);
        } else {
            // 未登录
            const localChannels = JSON.parse(
                localStorage.getItem(CHANNEL_KEY) ?? "[]"
            ) as Channel[];

            const userChannel = localChannels.filter(
                (item) => item.id !== channel.id
            );
            localStorage.setItem(CHANNEL_KEY, JSON.stringify(userChannel));
        }
        dispatch({ type: "home/delChannel", payload: channel });
        dispatch(getAllChannel());
    };
};
// 添加频道(重置)
export const addChannel = (channel: Channel): RootThunkAction => {
    return async (dispatch, getState) => {
        const {
            login: { token },
        } = getState();
        if (!!token) {
            // 登录
            await http.patch("/user/channels", {
                channels: [channel],
            });
        } else {
            const userChannel = [
                ...(JSON.parse(
                    localStorage.getItem(CHANNEL_KEY) ?? "[]"
                ) as Channel[]),
                channel,
            ];
            localStorage.setItem(CHANNEL_KEY, JSON.stringify(userChannel));
        }
        dispatch({ type: "home/addChannel", payload: channel });
    };
};
// 获取文章列表
export const getArticleList = (
    channel_id: number,
    timestamp: string
): RootThunkAction => {
    return async (dispatch) => {
        const res = await http.get<ApiRes<Articles>>("/articles", {
            params: {
                channel_id,
                timestamp,
            },
        });
        dispatch({
            type: "home/getChannelArticles",
            payload: {
                channelId: channel_id,
                data: res.data.data,
            },
        });
    };
};
